import Vue from 'vue'
import { debounce } from '@u/lodash/throttle'

const global = {isRouterJump: false};

const wx_auth_url = '';

function Authorize (opts = {}) {
    const {addToUrlQuery, qs} = Vue.$global_util;
    let href = addToUrlQuery(opts.url, {...opts.query, isAuthorize: 1});
    if (!/^https?:\/\//g.test(href)) {
        href = window.location.origin + '/consumer/' + href.replace(/^\//, '')
    }
    const query = qs.stringify({
        scope: 'snsapi_userinfo',
        type: 1,
        redirect_uri: href
    });
    const url = `${wx_auth_url}?${query}}`;
    if (type === '__blank') {
        window.location.replace(url)
    } else {
        window.location.href = url
    }
}

const routerLink = debounce(function () {
    const TAB_LINK = Vue.TAB_LINK;
    const util = Vue.$global_util;
    const {addToUrlQuery, ApJSBridge, getCurrentPage, mapKeys, qs, jude} = util;
    let type = arguments[1];
    let opts = arguments[0];
    let flag = true;
    let QUERY = {};
    // if (global.isRouterJump) return;
    if (jude.isNumberOfNaN(opts)) {
        if (opts <= 0) return;
        opts = {
            delta: opts,
            complete: function () {
            }
        };
        type = '__back';
    } else if (typeof opts === "string") {
        if (!opts.trim()) return;
        opts = {
            url: opts,
            complete: function () {
            }
        }
    } else if (!jude.isEmptyObject(opts, true)) {
        let obj = {
            success () {
            },
            fail () {
            },
            complete () {
            }
        };
        if (type === '__back') {
            obj.delta = 1;
            mapKeys(opts, obj, Object.keys(obj));
            if (jude.isNumberOfNaN(obj.delta)) return;
        } else {
            let obj2 = {
                url: '',
                name: '',
                isAuthorize: false,
                isToMiniProgram: false,
                params: {},
                query: {},
                ...obj
            };
            if (!jude.isEmpty(opts.path) && !opts.url) {
                opts.url = opts.path
            }
            if (opts.url) {
                delete obj2.name;
                delete obj2.params;
            } else if (opts.name) {
                delete obj2.url;
                delete obj2.query;
            }
            mapKeys(opts, obj, Object.keys(obj2));
            if (!obj.url && !opts.name) return;
            // if (jude.isObject(obj.query) && !jude.isEmptyObject(obj.query)) {
            //     if (/^https?:\/\//.test(opts.url)) {
            //         QUERY = {...obj.query}
            //     } else if (/\?/g.test(obj.url)) {
            //         obj.url += '&' + qs.stringify(obj.query)
            //     } else {
            //         obj.url += '?' + qs.stringify(obj.query)
            //     }
            // }
        }
        opts = obj;
    } else {
        return;
    }
    const fIndex = TAB_LINK.findIndex(v => new RegExp(v).test(opts.url));
    if (fIndex > -1) type = '__tab';

    const complete = opts.complete;
    opts.complete = function (obj) {
        typeof complete === 'function' && complete(...arguments);
    };
    if (/^pages\//g.test(opts.url)) opts.url = '/' + opts.url;

    //#ifdef H5
    if (opts.isAuthorize && (Vue.$device.isWechat || Vue.$device.isAlipay)) {
        return Authorize(opts);
    }
    //#endif

    if (/^https?:\/\//.test(opts.url)) {
        let url2 = opts.url;
        let page = getCurrentPage();
        let query = {isRedirect: 1};
        try {
            query = Object.assign(page.__options.query, query)
        } catch (e) {

        }
        let currUrl = page.route + '?' + qs.stringify(query);
        opts.url = '/pages/webView/index' + '?' + qs.stringify({
            url: url2,
            redirectUrl: currUrl,
            ...QUERY
        });
        flag = true;
        //#ifdef H5
        if (Vue.$device.isAlipay && opts.url.indexOf('mmtcapp.com') === -1) {
            ApJSBridge('pushWindow', {
                url: url2,
                param: {
                    readTitle: true,
                    showOptionMenu: false
                }
            });
            return;
        } else if (!Vue.$device.isWechat && opts.url.indexOf('mmtcapp.com') === -1) {
            if (type === '__blank') {
                window.location.replace(url2)
            } else {
                window.location.href = url2
            }
            return;
        }
        //#endif
    }

    let miniProgram = {}, isToMiniProgram = false;
    //#ifdef H5
    miniProgram = Vue.$wx_jssdk && Vue.$wx_jssdk.miniProgram;
    isToMiniProgram = Vue.$device.isMiniWechat && !jude.isEmptyObject(miniProgram, true) && opts.isToMiniProgram === true;
    //#endif
    console.log(opts, '跳转');
    if (flag) {
        global.isRouterJump = true;
        if (!isToMiniProgram && false) {
            opts.path = opts.url;
            delete opts.url;
        } else {
            opts.url = addToUrlQuery(opts.url, {...opts.query})
        }
        const cur = util.getCurrentPage().$vm;
        // if (!isToMiniProgram && opts.query) {
        //     // let str = JSON.stringify(opts.query);
        //     // opts.query = {_query: zip(str)};
        //     // console.log(zip(str), encodeURIComponent(str).length);
        //     let str = JSON.stringify(opts.query);
        //     str = lzw_compress(str);
        //     console.log(zip(str), encodeURIComponent(str).length, str);
        // }
        switch (true) {
            case type === '__blank':
                if (isToMiniProgram) return miniProgram.redirectTo(opts);
                uni.redirectTo(opts);
                // cur.$Router.replace(opts);
                break;
            case type === '__blanks':
                if (isToMiniProgram) return miniProgram.reLaunch(opts);
                uni.reLaunch(opts);
                // cur.$Router.replaceAll(opts);
                break;
            case type === '__tab':
                if (isToMiniProgram) return miniProgram.switchTab(opts);
                // uni.switchTab(opts);
                uni.reLaunch(opts);
                // cur.$Router.replaceAll(opts);
                break;
            case type === '__back':
                if (isToMiniProgram) return miniProgram.navigateBack(opts);
                const page = Vue.$global_util.getCurrentPage(1);
                if (page.route) {
                    uni.navigateBack(opts);
                } else {
                    uni.reLaunch({url: '/pages/home/index'});
                }
                // const {delta} = opts;
                // cur.$Router.back(delta);
                break;
            default:
                if (isToMiniProgram) return miniProgram.navigateTo(opts);
                uni.navigateTo(opts);
            // cur.$Router.push(opts)
        }
    }
}, 200)


Vue.mixin({
    onShow: function () {
        global.isRouterJump = false;
    }
});


class CustomRouter {
    constructor ($route) {

    }

    push (opts) {
        routerLink(opts);
    }

    replace (opts) {
        routerLink(opts, '__blank');
    }

    replaceAll (opts) {
        routerLink(opts, '__blanks');
    }

    pushTab (opts) {
        routerLink(opts, '__tab');
    }

    back (opts = 1) {
        routerLink(opts, '__back');
    }
}

const $$router = new CustomRouter();

Vue.$$router = $$router;
Vue.prototype.$$router = $$router;
